package com.supermap.application.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;


/**
 * @ClassName HttpClientUtils
 * @Description TODO
 * @Author HEKE
 * @Date 2019/2/27 17:22
 */
public class HttpClientUtils {

    /**
     * post请求 application/json
     * @param url
     * @param map
     * @return
     */
    public static String doAddPost(String url, Map<String,Object> map){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().
                setSocketTimeout(10000).setConnectTimeout(20000)
                .setConnectionRequestTimeout(10000).build();

        httpPost.setConfig(requestConfig);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status",map.get("status"));
        jsonObject.put("userName",map.get("userName"));
        jsonObject.put("userCaption",map.get("userCaption"));
        jsonObject.put("password",map.get("password"));
        jsonObject.put("passwordConfirm",map.get("passwordConfirm"));
        jsonObject.put("majors",map.get("majors"));
        jsonObject.put("userRegion",map.get("userRegion"));
        jsonObject.put("userPartment",map.get("userPartment"));
        jsonObject.put("phone",map.get("phone"));
        jsonObject.put("email",map.get("email"));
        jsonObject.put("sys_role",map.get("sys_role"));
        jsonObject.put("roleid",map.get("roleid"));
        jsonObject.put("flagA",map.get("flagA"));

        StringEntity entity = new StringEntity(jsonObject.toString(),"UTF-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        /*String context = StringUtils.EMPTY;
        if (!StringUtils.isEmpty(data)){
            StringEntity body = new StringEntity(data, "UTF-8");
        }*/
        // 设置回调接口接收的消息头
        httpPost.addHeader("Content-Type", "application/json");//application/x-www-form-urlencoded   application/json
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity entity2 = response.getEntity();

            String s = EntityUtils.toString(entity2, HTTP.UTF_8);
            return s;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
                httpPost.abort();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * post请求 参数map
     * @param url
     * @param params
     * @return
     */
    public static String doUpdatePost(String url, Map<String,Object> params){

        CloseableHttpClient httpClient = HttpClients.createDefault();

        CloseableHttpResponse response = null;

        HttpPost httpPost = new HttpPost(url);

        /**
         * 添加请求参数
         */
        List<NameValuePair> list = new LinkedList<>();

        BasicNameValuePair param1 = new BasicNameValuePair("userid",params.get("userid") + "");
        BasicNameValuePair param2 = new BasicNameValuePair("status",params.get("status") + "");
        BasicNameValuePair param3 = new BasicNameValuePair("userName",params.get("userName") + "");
        BasicNameValuePair param4 = new BasicNameValuePair("userCaption",params.get("userCaption") + "");
        BasicNameValuePair param5 = new BasicNameValuePair("password",params.get("password") + "");
        BasicNameValuePair param6 = new BasicNameValuePair("majors",params.get("majors") + "");
        BasicNameValuePair param7 = new BasicNameValuePair("userRegion",params.get("userRegion") + "");
        BasicNameValuePair param8 = new BasicNameValuePair("userPartment",params.get("userPartment") + "");
        BasicNameValuePair param9 = new BasicNameValuePair("phone",params.get("phone") + "");
        BasicNameValuePair param10 = new BasicNameValuePair("email",params.get("email") + "");
        BasicNameValuePair param11 = new BasicNameValuePair("sys_role",params.get("sys_role") + "");
        BasicNameValuePair param12 = new BasicNameValuePair("flagA",params.get("flagA") + "");

        list.add(param1);
        list.add(param2);
        list.add(param3);
        list.add(param4);
        list.add(param5);
        list.add(param6);
        list.add(param7);
        list.add(param8);
        list.add(param9);
        list.add(param10);
        list.add(param11);
        list.add(param12);

        try {
            UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(list,"UTF-8");
            httpPost.setEntity(encodedFormEntity);

            // 浏览器表示
            httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
            // 传输的类型
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");

            response = httpClient.execute(httpPost);

            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 删除请求
     * @param url
     * @param data
     * @return
     */
    public static String doDeletePost(String url, String data){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().
                setSocketTimeout(10000).setConnectTimeout(20000)
                .setConnectionRequestTimeout(10000).build();

        httpPost.setConfig(requestConfig);


        /*String context = StringUtils.EMPTY;
        if (!StringUtils.isEmpty(data)){
            StringEntity body = new StringEntity(data, "UTF-8");
        }*/
        // 设置回调接口接收的消息头
        httpPost.addHeader("Content-Type", "application/json");//application/x-www-form-urlencoded   application/json
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity entity2 = response.getEntity();

            String s = EntityUtils.toString(entity2, HTTP.UTF_8);
            return s;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
                httpPost.abort();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * GET请求模拟登录
     * @param url
     * @return
     */
    public static String doGet(String url){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom().
                setSocketTimeout(10000).setConnectTimeout(20000)
                .setConnectionRequestTimeout(10000).build();
        httpGet.setConfig(requestConfig);

        // 设置回调接口接收的消息头
        //httpGet.addHeader("Content-Type", "application/json;charset=UTF-8");
        CloseableHttpResponse response = null;

        try {
            response = httpClient.execute(httpGet);
            /*Header[] headers = response.getHeaders("Set-Cookie");
            String sessionId = headers[0].getValue();
            String[] split = sessionId.split(";");
            String session = split[0];*/

            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            /*int statusCode = response.getStatusLine().getStatusCode();
               result.put("statusCode",statusCode);*/
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
                if (response != null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

}
